import { WeaBrowser } from 'ecCom';

import { isArray, each, set } from 'lodash';
import { toJS } from 'mobx';
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { searchPngImg, requiredPngImg } from '.';
import { WeaLocaleProvider } from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;

export default class WeaBrowserCellType extends GC.Spread.Sheets.CellTypes.Base {
    typeName = 'WeaBrowserCellType';
    fieldType;
    browserType;
    browserTitile;
    dataParams = {};
    tabs = [];
    viewAttr = 2;
    label;
    expandType;
    combineSameCell;
    clickwidth;
    id;
    tableName;
    multilang;
    fieldVisible;
    paint(ctx, value, x, y, w, h, style, context) {
        if(this.fieldVisible == '1') {
            this.viewAttr = 1;
            return;
        }
        if (!ctx) {
            return;
        }
        if (this.viewAttr != 1) {
            let iconWidth = 16;
            if(this.iconWidth) iconWidth = this.iconWidth;
            super.paint(ctx, value, x, y, w - 20, h, style, context);
            super.paint(ctx, '', x + w - 20, y, 20, h, style, context);
            const width = Math.min(iconWidth, h);
            if (this.viewAttr == 2) {
                this.clickwidth = width;
                ctx.drawImage(searchPngImg, x + w - width, y + (h - width) / 2, width, width);
            } else if (this.viewAttr == 3) {
                if (value && value.length > 0) {
                    this.clickwidth = width;
                    ctx.drawImage(searchPngImg, x + w - width, y + (h - width) / 2, width, width);
                } else {
                    this.clickwidth = width + 9;
                    ctx.drawImage(searchPngImg, x + w - this.clickwidth, y + (h - width) / 2, width, width);
                    ctx.drawImage(requiredPngImg, x + w - 8, y + (h - 7) / 2, 7, 7);
                }

            }

        } else {
            super.paint(ctx, value, x, y, w, h, style, context);
        }

    }
    format(value, format, formattedData, context) {
        if (isArray(value)) {
            return value.filter(d => typeof d !== 'function').map(d => this.delHtmlTag(d.names || d.name)).join(',');
        } else {
            return '';
        }
    }
    fromJSON(setting) {
        this.fieldType = toJS(setting.fieldType);
        this.viewAttr = setting.viewAttr;
        this.fieldVisible = setting.fieldVisible;
        this.label = setting.label;
        this.browserType = this.fieldType[1].value;
        this.expandType = setting.expandType;
        this.combineSameCell = setting.combineSameCell;
        this.id = setting.id;
        this.tableName = setting.tableName;
        this.multilang = setting.multilang;
        if (this.fieldType.length == 2) {

            this.browserTitile = this.fieldType[1].valueSpan;
        } else {
            if (this.fieldType[1]["valueObj"]) {
                this.browserTitile = this.fieldType[1]["valueObj"][0].name;
            } else {
                this.browserTitile = this.fieldType[1].valueSpan;
            }

        }

        if (this.browserType === '161' || this.browserType === '162') {
            this.dataParams = { type: (this.fieldType[2] || {}).value }
        } else if (this.browserType === '256' || this.browserType === '257') {
            this.dataParams = { ...this.dataParams, cube_treeid: (this.fieldType[2] || {}).value }
        } else if (this.browserType == '171') {
            this.dataParams = { ...this.dataParams, status: 2 };
        }
        if (this.browserType === '4' || this.browserType === '57' || this.browserType === '167' || this.browserType === '168') {
            this.tabs = {
                tabs: [{
                    "key": "2",
                    "name": getLabel('505968', '组织结构'),
                    "dataURL": null,
                    "dataParams": null,
                    "isSearch": false,
                    "showOrder": 0,
                    "selected": false
                }, {
                    "key": "1",
                    "name": getLabel('505969', '按列表'),
                    "dataURL": null,
                    "dataParams": {
                        "list": "1"
                    },
                    "isSearch": true,
                    "showOrder": 0,
                    "selected": false
                }]
            };
        } else if (this.browserType === '164' || this.browserType === '169' || this.browserType === '170' || this.browserType === '194') {
            this.tabs = {
                tabs: [{
                    "key": "2",
                    "name": getLabel('505968', '组织结构'),
                    "dataURL": null,
                    "dataParams": null,
                    "isSearch": false,
                    "showOrder": 0,
                    "selected": false
                }, {
                    "key": "1",
                    "name": getLabel('505969', '按列表'),
                    "dataURL": null,
                    "dataParams": {
                        "list": "1"
                    },
                    "isSearch": true,
                    "showOrder": 0,
                    "selected": false
                }]
            };
        } else if (this.browserType === '142') {
            this.tabs = {
                tabs: [{
                    "dataParams": { "cmd": "List" },
                    "isSearch": true,
                    "key": "1",
                    "name": "列表",
                    selected: false,
                    showOrder: 0
                },
                {
                    "dataParams": { cmd: "Organization" },
                    "isSearch": false,
                    "key": "2",
                    "name": "组织结构",
                    "selected": false,
                    "showOrder": 0
                },
                {
                    "dataParams": { "cmd": "PublicGroup" },
                    "isSearch": false,
                    "key": "3",
                    "name": "公共组",
                    "selected": false,
                    "showOrder": 0
                },
                {
                    "dataParams": { "cmd": "PrivateGroup" },
                    "isSearch": false,
                    "key": "4",
                    "name": "私人组",
                    "selected": false,
                    "showOrder": 0
                },
                {
                    "dataParams": { "companyType": "1", "cmd": "ExternalUnit" },
                    "isSearch": false,
                    "key": "5",
                    "name": "外部单位",
                    "selected": false,
                    "showOrder": 0
                }]
            };
        } else if (this.browserType === '22') {
            this.tabs={
                tabs:[{
                    "dataParams": { "list": "1" },
                    "isSearch": true,
                    "key": "1",
                    "name": getLabel(516807,"最近"),
                    "selected": false,
                    "showOrder": 0
                },{
                    "isSearch": false,
                    "key": "2",
                    "name": getLabel(516808,"按科目结构"),
                    "selected": false,
                    "showOrder": 0 
                }]
            };
        } else {
            this.tabs = {};
        }
        this.isSingle = setting.isSingle;
        this.isMultCheckbox = setting.isMultCheckbox;
    }
    doUpdateValue = (context, value) => {
        context.value(value);
    }
    getHitInfo(x, y, cellStyle, cellRect, context) {
        const { row, col, sheetArea, sheet } = context;
        return {
            x,
            y,
            row,
            col,
            cellRect,
            sheetArea,
            sheet,
        };
    }
    processMouseUp(hitInfo) {
        // 只读 不展示
        if (this.viewAttr && this.viewAttr == 1) {
            return;
        }
        const { x, y, cellRect, sheet, row, col, sheetArea, reservedLocation, isReservedLocation } = hitInfo;
        if (x && cellRect) {
            if (x >= cellRect.x + cellRect.width - this.clickwidth) {
                this.showBrowserModal(sheet.getCell(row, col, sheetArea), cellRect);
            }
            return true;
        }
        return super.processMouseUp(hitInfo);
    }

    delHtmlTag(str) {
        if (str) {
            //去掉所有的html标记
            return str.replace(/<[^>]+>/g, "");
        }
    }

    showBrowserModal(context, cellRect) {
        // 只读 不展示
        if (this.viewAttr && this.viewAttr == 1) {
            return;
        }
        const { sheet, row, col } = context;
        let editor;
        if (!editor) {
            editor = document.createElement('div');
            const host = sheet.getParent().getHost();
            host.appendChild(editor);
            editor.style.visibility = 'hidden';
            $(editor).css({
                position: 'absolute',
                left: cellRect.x,
                top: cellRect.y,
                width: cellRect.width,
                height: cellRect.height,
            });
        }

        ReactDOM.unmountComponentAtNode(editor);

        const replaceDatas = context.value();

        const changeValue = (newValue, valueSpan, valueObj) => {
            sheet.getCell(row, col).value((valueObj || []).map(d => ({ id: d.id, name: this.delHtmlTag(d.name) })));
        }
        const getMainFieldName = (path) => {
            const strs = path.split(".");
            return strs[strs.length - 1]
        }
        const getFieldValue = (value) => {
            let returnValue = "";
            if (value && Array.isArray(value)) {
                returnValue = value.map(o => (o.id)).join(",");
            } else {
                returnValue = value;
            }
            return String(returnValue);
        }
        const getFormData = () => {
            const sqlNeedFieldKey = (this.fieldType[2] || {}).sqlNeedFieldKey;
            const { currenttime: oldCurrenttime } = this.dataParams;
            let fields = {};
            const mainFields = {};
            const detailFields = {};
            const table = sheet.tables.find(row, col);
            if (table) {
                //明细表
                const dataRange = table.dataRange();
                const { colCount, col: startCol } = dataRange;
                for (let i = 0; i < colCount; i++) {
                    const cell = sheet.getCell(Number(row), Number(startCol + i));
                    const cellType = cell.cellType();
                    if (cellType && cellType.fieldType) {
                        const fieldname = table.getColumnDataField(i);
                        set(detailFields, `${this.tableName}_${fieldname}`, getFieldValue(cell.value()));
                    }
                }
            }
            //主表
            const { data } = sheet.toJSON();
            if (data) {
                const { dataTable } = data;
                if (dataTable) {
                    each(dataTable, (o, rowIndex) => {
                        each(o, (obj, colIndex) => {
                            const bindingPath = sheet.getBindingPath(rowIndex, colIndex);
                            if (bindingPath) {
                                const cell = sheet.getCell(Number(rowIndex), Number(colIndex));
                                const cellType = cell.cellType();
                                if (cellType && cellType.fieldType) {
                                    const fieldname = getMainFieldName(bindingPath);
                                    const value = getFieldValue(cell.value());
                                    mainFields[`${fieldname}`] = value;

                                }
                            }
                        });
                    });
                }
            }
            if (sqlNeedFieldKey) {
                const currenttime = new Date().getTime();
                fields = { ...fields, currenttime };
                each(sqlNeedFieldKey, (key, index) => {
                    if (_.parseInt(index) % 2 === 0) {//主表
                        delete this.dataParams[`${key}_${oldCurrenttime}`];
                        const value = mainFields[key];
                        if (value !== void 0) {
                            fields[`${key}_${currenttime}`] = mainFields[key];
                        }
                    } else {
                        delete this.dataParams[`${this.tableName}_${key}_${oldCurrenttime}`];
                        const value = detailFields[`${this.tableName}_${key}`];
                        if (value !== void 0) {
                            fields[`${this.tableName}_${key}_${currenttime}`] = value;
                        }
                    }
                });
            }
            return fields;
        }
        if (this.browserType === '161' || this.browserType === '162' || this.browserType === '256' || this.browserType === '257') {
            const formData = getFormData();
            this.dataParams = { ...this.dataParams, ...formData };
        }
        let browserInstance;
        ReactDOM.render(<WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@v7hkfx`}
            hasAdvanceSerach={true}
            conditionDataParams={this.dataParams}
            ref={(ref) => browserInstance = ref}
            onChange={changeValue}
            dataParams={this.dataParams}
            destDataParams={this.dataParams}
            replaceDatas={(replaceDatas || [])}
            memorise={true}
            type={this.browserType}
            title={this.browserTitile}
            iconBgcolor={"#217346"}
            isSingle={this.isSingle}
            isMultCheckbox={this.isMultCheckbox}
            {...this.tabs}
        />, editor);
        const openModal = () => {
            if (browserInstance) {
                browserInstance.openModal();
            } else {
                setTimeout(() => {
                    openModal();
                }, 50);
            }
        }
        openModal();
    }
}